package cn.kgc.vue.shiro;

import cn.kgc.vue.filters.WebTokenFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/4/9
 * @description  安全框架shiro配置类
 */
@Configuration
public class ShiroWebConfig {

    // shiro过滤器链
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 添加自定义filter 到 shiroFilterFactoryBean
        HashMap<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("customer",new WebTokenFilter());
        shiroFilterFactoryBean.setFilters(filterHashMap);

        // 设置过滤器的拦截规则
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        //放行请求
        linkedHashMap.put("/captcha","anon");
        linkedHashMap.put("/user/login","anon");

        // 放行swagger相关静态资源
        linkedHashMap.put("/doc.html","anon");
        linkedHashMap.put("/swagger-resources", "anon");
        linkedHashMap.put("/favicon.ico", "anon");
        linkedHashMap.put("/v2/api-docs", "anon");
        linkedHashMap.put("/webjars/css/app.b2512131.css", "anon");
        linkedHashMap.put("/webjars/js/chunk-vendors.9ff0f717.js", "anon");
        linkedHashMap.put("/webjars/js/app.ed549958.js", "anon");


        linkedHashMap.put("/**","customer");

        // 用户未认证时跳转的路径
        shiroFilterFactoryBean.setLoginUrl("/user/unAuthenticate");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return  shiroFilterFactoryBean;
    }

    // 安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }

    // 自定义域对象
    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }

}
